package com.lemi.common.base.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lemi.common.base.dao.BaseDao;
import com.lemi.common.base.entity.BaseEntity;
import com.lemi.common.base.service.BaseService;
import com.lemi.common.exception.BaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author kevin
 * @since 2020/7/3 2:22 PM
 */
@Transactional(rollbackFor = {Exception.class})
public class BaseServiceImpl<R extends BaseDao, E extends BaseEntity> implements BaseService<E> {

    @Autowired
    protected R dao;

    @Override
    public E findById(String id) {
        return (E) this.dao.selectByPrimaryKey(id);
    }

    @Override
    public List<E> findAll() {
        return this.dao.select(null);
    }

    @Override
    public E findOne(E e) {
        List<E> result =  this.dao.select(e);
        if (result != null && result.size() > 0){
            return result.get(0);
        }
        return null;
    }

    @Override
    public List<E> findListByWhere(E e) {
        return this.dao.select(e);
    }

    @Override
    public PageInfo<E> findPageListByWhere(Integer pageNum, Integer pageSize, E e) {
        // 设置分页条件
        PageHelper.startPage(pageNum, pageSize);
        List<E> list = this.findListByWhere(e);
        return new PageInfo<>(list);
    }


    @Override
    public Integer saveSelective(E e) {
        e.setDelFlag(false);
        e.setCreateTime(new Date());
        return this.dao.insertSelective(e);
    }

    @Override
    public Integer insertAndGetId(E e) {
        saveSelective(e);
        return e.getId();
    }

    @Override
    public E insertSelective(E e) {
        saveSelective(e);
        return e;
    }

    @Override
    public Integer update(E e) {
        return updateSelective(e);
    }

    @Override
    public Integer updateSelective(E e) {
        e.setUpdateTime(new Date());
        long version = ((E) this.dao.selectByPrimaryKey(e.getId())).getVersion();
        e.setVersion(version);
        int i = this.dao.updateByPrimaryKeySelective(e);
        if (i<=0){
            throw new BaseException("更新失败");
        }
        return i;
    }

    public List<E> selectByExample(Object example) {
        return dao.selectByExample(example);
    }
}
